const express = require("express")
const router = express.Router()

const {User} = require("../../models")

const {NotFound} = require("http-errors")
const {success} = require("../../utils/response");


/**
 * 查询用户列表
 */
router.get("/", async (req, res, next) => {
    try {
        let query = req.query

        console.log(req.user)

        const currentPage = Math.abs(Number(query.currentPage)) || 1
        const pageSize = Math.abs(Number(query.pageSize)) || 10
        const offset = (currentPage - 1) * pageSize

        const condition = {
            order: [['id', 'DESC']],
            where: {},
            limit: pageSize,
            offset: offset
        }

        const {count, rows} = await User.findAndCountAll(condition)
        success(res, "查询用户列表成功", {
            users: rows,
            pagination: {
                total: count,
                currentPage,
                pageSize,

            }
        })

    } catch (err) {
        next(err);
    }
})

/**
 * 查询用户详情
 */
router.get("/:id", async (req, res, next) => {
    try {
        const data = await getUser(req)
        success(res, "查询用户详情成功", data)
    } catch(err) {
        next(err)
    }
})

/**
 * 创建用户
 */
router.post("/", async (req, res, next) => {
    try {
        const body = filterBody(req)
        const data = await User.create(body)
        success(res, "创建用户成功", data, 201)
    } catch(err) {
        next(err)
    }
})

/**
 * 删除用户
 */
router.delete("/:id", async (req, res, next) => {
    try {
        let user = await getUser(req)
        await user.destroy()
        success(res, "删除用户成功")
    } catch(err) {
        next(err)
    }
})

/**
 * 修改用户成功
 */
router.put('/:id', async (req, res, next) => {
    try {
        const user = await getUser(req)
        const body = filterBody(req)

        await user.update(body)

        success(res, "修改用户成功", {user})

    } catch (err) {
        next(err)
    }
})

function filterBody(req) {
    return {
        name: req.body.name,
        email: req.body.email,
        password: req.body.password,
        role: req.body.role,
    }
}

async function getUser(req) {
    const {id} = req.params
    const user = await User.findByPk(id)

    if(!user) {
        throw new NotFound(`ID：${id}的用户未找到`)
    }
    return user
}

module.exports = router